<?php
class ProductController extends Controller
{
	/**
	 * @var string 默认使用的布局文件。
	 * 默认值为 '//layouts/column2', 表示使用2栏布局。
	 * 布局文件的路径为 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * 显示指定的产品信息
	 * @param integer 要显示的产品id
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));

	}

	/**
	 * 创建一个产品
	 * 成功创建产品后跳转到管理页面
	 */
	public function actionCreate()
	{
		$model=new Product;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];

			if($model->save())
			{
				if(isset(Yii::app()->session['productPicture'])){
					foreach(Yii::app()->session['productPicture'] as $picture_id){
						$picture=ProductPicture::model()->findByPk($picture_id);
		            	$picture->product_id = $model->id;
		            	$picture->save();
					}
					if(!isset($model->cover))
					{
						$model->cover = Yii::app()->session['productPicture'][0];
						$model->save();
					}
	            	unset(Yii::app()->session['productPicture']);
	            }
                $this->redirect(array('product/index'));
			}
		}
		else
		{
			if(isset(Yii::app()->session['productPicture'])){
            	unset(Yii::app()->session['productPicture']);
            }
		}

		$this->render('create',array('model'=>$model));
	}

	/**
	 * 更新指定的产品
	 * 更新成功后会跳转到管理页面
	 * @param integer 要更新的产品id
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];

			if($model->save())
			{
				if(isset(Yii::app()->session['productPicture'])){
					foreach(Yii::app()->session['productPicture'] as $picture_id){
						$picture=ProductPicture::model()->findByPk($picture_id);
		            	$picture->product_id = $model->id;
		            	$picture->save();
					}
					if(!isset($model->cover))
					{
						$model->cover = Yii::app()->session['productPicture'][0];
						$model->save();
					}
	            	unset(Yii::app()->session['productPicture']);
	            }

	            $this->redirect(array('product/index'));
			}
		}
		else
		{
			if(isset(Yii::app()->session['productPicture'])){
            	unset(Yii::app()->session['productPicture']);
            }
		}

        $this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * 删除指定的产品
	 * 在AJAX模式，当删除成功后，数据表格会被刷新
	 * 而在普通模式则会跳转到管理页面
	 * @param integer 要删除的产品id
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);

		if(Yii::app()->request->isAjaxRequest)
		{
			// 禁止jQuery 重复初始化
	        Yii::app()->clientScript->scriptMap['jquery.js'] = false;

			if(isset($_POST['action']) && $_POST['action'] == 'confirmDelete')
			{
				// 删除生成的3种尺寸的图片
				foreach ($model->pictures as $picture) {
					$dir=Yii::app()->basePath."/../uploads/product/";
					$file=$picture->name.".".$picture->ext;
					Util::deletePictures($dir, $file);
				}

				// 删除模型
				$model->delete();

				echo CJSON::encode( array(
					'status' => 'success',
					'content' => '<div class="tips tips-ok">
				        <i class="ico-ok"></i>
				        <div class="cont">
				            <h4>Info</h4>
				            <p>Deleted succussfully.</p>
				        </div>
				    </div>',
					));
				exit;
			}
			else if(isset($_POST['action']))
			{
				echo CJSON::encode( array(
					'status' => 'canceled',
					'content' => '<div class="tips tips-info">
				        <i class="ico-info"></i>
				        <div class="cont">
				            <h4>Info</h4>
				            <p>Deleted canceled.</p>
				        </div>
				    </div>',
					));
				exit;
			}
			else
			{
				echo CJSON::encode( array(
					'status' => 'failure',
					'content' => $this->renderPartial('delete', array(
						'model' => $model ), true, true),
					));
				exit;
			}
		}
		else
		{
			if(isset($_POST['confirmDelete']))
			{
				// 删除生成的3种尺寸的图片
				foreach ($model->pictures as $picture) {
					$dir=Yii::app()->basePath."/../uploads/product/";
					$file=$picture->name.".".$picture->ext;
					Util::deletePictures($dir, $file);
				}

				// 删除模型
				$model->delete();
				$this->redirect(array('admin'));
			}
			else if(isset($_POST['denyDelete']))
				$this->redirect(array('view','id' => $model->id));
			else
				$this->render('delete', array('model' => $model));
		}
	}

	public function actionSetCover()
	{
		if(Yii::app()->request->isAjaxRequest)
		{

			if(isset($_POST['pictureId']))
			{
				$pictureId = $_POST['pictureId'];
				$picture = ProductPicture::model()->findByPk($pictureId);
				$product = $picture->product;
				$product->cover = $pictureId;

				if($product->save())
				{
					echo CJSON::encode( array(
						'status' => 'success',
						'content' => '<div class="tips tips-ok">
					        <i class="ico-ok"></i>
					        <div class="cont">
					            <h4>Info</h4>
					            <p>Cover set succussfully.</p>
					        </div>
					    </div>',
						));
					exit;
				}
			}
		}
		
	}

	/**
	 * Lists all models.
	 */
	//public function actionIndex()
	//{
		//$dataProvider=new CActiveDataProvider('Product');
		//$this->render('index',array(
			//'dataProvider'=>$dataProvider,
		//));
	//}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Product']))
			$model->attributes=$_GET['Product'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Product::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}
